{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### test GeoMAN"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "d:\\ProgramData\\Anaconda3\\lib\\site-packages\\h5py\\__init__.py:34: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`.\n",
      "  from ._conv import register_converters as _register_converters\n"
     ]
    }
   ],
   "source": [
    "import tensorflow as tf\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "from matplotlib import pyplot as plt\n",
    "import os\n",
    "import json\n",
    "import math\n",
    "import pickle\n",
    "from utils import basic_hyperparams\n",
    "from utils import load_data\n",
    "from utils import load_global_inputs\n",
    "from utils import get_valid_batch_feed_dict"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def root_mean_squared_error(labels, preds):\n",
    "    total_size = np.size(labels)\n",
    "    return np.sqrt(np.sum(np.square(labels - preds)) / total_size)\n",
    "\n",
    "def mean_absolute_error(labels, preds):\n",
    "    total_size = np.size(labels)\n",
    "    return np.sum(np.abs(labels - preds)) / total_size"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# use specific gpu\n",
    "os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\"\n",
    "tf_config = tf.ConfigProto()\n",
    "tf_config.gpu_options.allow_growth = True"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "HParams([('dropout_rate', 0.3), ('ext_flag', True), ('gc_rate', 2.5), ('gpu_id', '0'), ('lambda_l2_reg', 0.001), ('learning_rate', 0.001), ('n_external_input', 83), ('n_hidden_decoder', 128), ('n_hidden_encoder', 128), ('n_input_decoder', 1), ('n_input_encoder', 19), ('n_output_decoder', 1), ('n_sensors', 35), ('n_stacked_layers', 2), ('n_steps_decoder', 6), ('n_steps_encoder', 12), ('s_attn_flag', 2)])"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# load hyperparameters\n",
    "session = tf.Session(config=tf_config)\n",
    "hps = basic_hyperparams()\n",
    "hps_dict = json.load(open('./hparam_files/AirQualityGeoMan.json', 'r'))\n",
    "hps.override_from_dict(hps_dict)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[('dropout_rate', 0.3), ('ext_flag', True), ('gc_rate', 2.5), ('gpu_id', '0'), ('lambda_l2_reg', 0.001), ('learning_rate', 0.001), ('n_external_input', 83), ('n_hidden_decoder', 128), ('n_hidden_encoder', 128), ('n_input_decoder', 1), ('n_input_encoder', 19), ('n_output_decoder', 1), ('n_sensors', 35), ('n_stacked_layers', 2), ('n_steps_decoder', 6), ('n_steps_encoder', 12), ('s_attn_flag', 2)]\n",
      "INFO:tensorflow:Summary name Weights_out:0 is illegal; using Weights_out_0 instead.\n",
      "INFO:tensorflow:Summary name Biases_out:0 is illegal; using Biases_out_0 instead.\n",
      "INFO:tensorflow:Summary name GeoMAN/Encoder/spatial_attn/local_spatial_attn/AttnUl:0 is illegal; using GeoMAN/Encoder/spatial_attn/local_spatial_attn/AttnUl_0 instead.\n",
      "INFO:tensorflow:Summary name GeoMAN/Encoder/spatial_attn/local_spatial_attn/AttnVl:0 is illegal; using GeoMAN/Encoder/spatial_attn/local_spatial_attn/AttnVl_0 instead.\n",
      "INFO:tensorflow:Summary name GeoMAN/Encoder/spatial_attn/global_spatial_attn/AttnW_and_u:0 is illegal; using GeoMAN/Encoder/spatial_attn/global_spatial_attn/AttnW_and_u_0 instead.\n",
      "INFO:tensorflow:Summary name GeoMAN/Encoder/spatial_attn/global_spatial_attn/AttnVg:0 is illegal; using GeoMAN/Encoder/spatial_attn/global_spatial_attn/AttnVg_0 instead.\n",
      "INFO:tensorflow:Summary name GeoMAN/Encoder/spatial_attn/multi_rnn_cell/cell_0/basic_lstm_cell/kernel:0 is illegal; using GeoMAN/Encoder/spatial_attn/multi_rnn_cell/cell_0/basic_lstm_cell/kernel_0 instead.\n",
      "INFO:tensorflow:Summary name GeoMAN/Encoder/spatial_attn/multi_rnn_cell/cell_0/basic_lstm_cell/bias:0 is illegal; using GeoMAN/Encoder/spatial_attn/multi_rnn_cell/cell_0/basic_lstm_cell/bias_0 instead.\n",
      "INFO:tensorflow:Summary name GeoMAN/Encoder/spatial_attn/multi_rnn_cell/cell_1/basic_lstm_cell/kernel:0 is illegal; using GeoMAN/Encoder/spatial_attn/multi_rnn_cell/cell_1/basic_lstm_cell/kernel_0 instead.\n",
      "INFO:tensorflow:Summary name GeoMAN/Encoder/spatial_attn/multi_rnn_cell/cell_1/basic_lstm_cell/bias:0 is illegal; using GeoMAN/Encoder/spatial_attn/multi_rnn_cell/cell_1/basic_lstm_cell/bias_0 instead.\n",
      "INFO:tensorflow:Summary name GeoMAN/Encoder/spatial_attn/local_spatial_attn/AttnWl/kernel:0 is illegal; using GeoMAN/Encoder/spatial_attn/local_spatial_attn/AttnWl/kernel_0 instead.\n",
      "INFO:tensorflow:Summary name GeoMAN/Encoder/spatial_attn/local_spatial_attn/AttnWl/bias:0 is illegal; using GeoMAN/Encoder/spatial_attn/local_spatial_attn/AttnWl/bias_0 instead.\n",
      "INFO:tensorflow:Summary name GeoMAN/Encoder/spatial_attn/global_spatial_attn/AttnWg/kernel:0 is illegal; using GeoMAN/Encoder/spatial_attn/global_spatial_attn/AttnWg/kernel_0 instead.\n",
      "INFO:tensorflow:Summary name GeoMAN/Encoder/spatial_attn/global_spatial_attn/AttnWg/bias:0 is illegal; using GeoMAN/Encoder/spatial_attn/global_spatial_attn/AttnWg/bias_0 instead.\n",
      "INFO:tensorflow:Summary name GeoMAN/Decoder/temporal_attn/Attn_Wd:0 is illegal; using GeoMAN/Decoder/temporal_attn/Attn_Wd_0 instead.\n",
      "INFO:tensorflow:Summary name GeoMAN/Decoder/temporal_attn/Attn_v:0 is illegal; using GeoMAN/Decoder/temporal_attn/Attn_v_0 instead.\n",
      "INFO:tensorflow:Summary name GeoMAN/Decoder/temporal_attn/kernel:0 is illegal; using GeoMAN/Decoder/temporal_attn/kernel_0 instead.\n",
      "INFO:tensorflow:Summary name GeoMAN/Decoder/temporal_attn/bias:0 is illegal; using GeoMAN/Decoder/temporal_attn/bias_0 instead.\n",
      "INFO:tensorflow:Summary name GeoMAN/Decoder/temporal_attn/multi_rnn_cell/cell_0/basic_lstm_cell/kernel:0 is illegal; using GeoMAN/Decoder/temporal_attn/multi_rnn_cell/cell_0/basic_lstm_cell/kernel_0 instead.\n",
      "INFO:tensorflow:Summary name GeoMAN/Decoder/temporal_attn/multi_rnn_cell/cell_0/basic_lstm_cell/bias:0 is illegal; using GeoMAN/Decoder/temporal_attn/multi_rnn_cell/cell_0/basic_lstm_cell/bias_0 instead.\n",
      "INFO:tensorflow:Summary name GeoMAN/Decoder/temporal_attn/multi_rnn_cell/cell_1/basic_lstm_cell/kernel:0 is illegal; using GeoMAN/Decoder/temporal_attn/multi_rnn_cell/cell_1/basic_lstm_cell/kernel_0 instead.\n",
      "INFO:tensorflow:Summary name GeoMAN/Decoder/temporal_attn/multi_rnn_cell/cell_1/basic_lstm_cell/bias:0 is illegal; using GeoMAN/Decoder/temporal_attn/multi_rnn_cell/cell_1/basic_lstm_cell/bias_0 instead.\n",
      "INFO:tensorflow:Summary name GeoMAN/Decoder/temporal_attn/Attn_Wpd/kernel:0 is illegal; using GeoMAN/Decoder/temporal_attn/Attn_Wpd/kernel_0 instead.\n",
      "INFO:tensorflow:Summary name GeoMAN/Decoder/temporal_attn/Attn_Wpd/bias:0 is illegal; using GeoMAN/Decoder/temporal_attn/Attn_Wpd/bias_0 instead.\n",
      "INFO:tensorflow:Summary name GeoMAN/Decoder/temporal_attn/AttnOutputProjection/kernel:0 is illegal; using GeoMAN/Decoder/temporal_attn/AttnOutputProjection/kernel_0 instead.\n",
      "INFO:tensorflow:Summary name GeoMAN/Decoder/temporal_attn/AttnOutputProjection/bias:0 is illegal; using GeoMAN/Decoder/temporal_attn/AttnOutputProjection/bias_0 instead.\n"
     ]
    }
   ],
   "source": [
    "# model construction\n",
    "tf.reset_default_graph()\n",
    "from GeoMAN import GeoMAN\n",
    "print(hps)\n",
    "model = GeoMAN(hps)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "test samples: 81751\n"
     ]
    }
   ],
   "source": [
    "# read data from test set\n",
    "input_path = './data/'\n",
    "test_data = load_data(\n",
    "    input_path, 'test', hps.n_steps_encoder, hps.n_steps_decoder)\n",
    "global_inputs, global_attn_states = load_global_inputs(\n",
    "    input_path, hps.n_steps_encoder, hps.n_steps_decoder)\n",
    "num_test = len(test_data[0])\n",
    "print('test samples: {0}'.format(num_test))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# read scaler of the labels\n",
    "f = open('./data/scalers/scaler-0.pkl', 'rb')\n",
    "scaler = pickle.load(f)\n",
    "f.close()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# path\n",
    "if hps.ext_flag:\n",
    "    if hps.s_attn_flag == 0:\n",
    "        model_name = 'GeoMANng'\n",
    "    elif hps.s_attn_flag == 1:\n",
    "        model_name = 'GeoMANnl'\n",
    "    else:\n",
    "        model_name = 'GeoMAN'\n",
    "else:\n",
    "    model_name = 'GeoMANne'\n",
    "model_path = './logs/{}-{}-{}-{}-{}-{:.2f}-{:.3f}/'.format(model_name,\n",
    "                                                           hps.n_steps_encoder,\n",
    "                                                           hps.n_steps_decoder,\n",
    "                                                           hps.n_stacked_layers,\n",
    "                                                           hps.n_hidden_encoder,\n",
    "                                                           hps.dropout_rate,\n",
    "                                                           hps.lambda_l2_reg)\n",
    "model_path += 'saved_models/final_model.ckpt'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# test params\n",
    "n_split_test = 500  # times of splitting test set\n",
    "test_rmses = []\n",
    "test_maes = []"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Starting loading model...\n",
      "INFO:tensorflow:Restoring parameters from ./logs/GeoMAN-12-6-2-128-0.30-0.001/saved_models/final_model.ckpt\n",
      "Model successfully restored from file: ./logs/GeoMAN-12-6-2-128-0.30-0.001/saved_models/final_model.ckpt\n",
      "===============METRIC===============\n",
      "rmse = 21.429615\n",
      "mae = 14.174139\n"
     ]
    }
   ],
   "source": [
    "# restore model\n",
    "print(\"Starting loading model...\")\n",
    "saver = tf.train.Saver()\n",
    "with tf.Session() as sess:\n",
    "    model.init(sess)\n",
    "\n",
    "    # Restore model weights from previously saved model\n",
    "    saver.restore(sess, model_path)\n",
    "    print(\"Model successfully restored from file: %s\" % model_path)\n",
    "\n",
    "    # test\n",
    "    test_loss = 0\n",
    "    test_indexes = np.int64(\n",
    "        np.linspace(0, num_test, n_split_test))\n",
    "    for k in range(n_split_test - 1):\n",
    "        feed_dict = get_valid_batch_feed_dict(\n",
    "            model, test_indexes, k, test_data, global_inputs, global_attn_states)\n",
    "        # re-scale predicted labels\n",
    "        batch_preds = sess.run(model.phs['preds'], feed_dict)\n",
    "        batch_preds = np.swapaxes(batch_preds, 0, 1)\n",
    "        batch_preds = np.reshape(batch_preds, [batch_preds.shape[0], -1])\n",
    "        batch_preds = scaler.inverse_transform(batch_preds)\n",
    "        # re-scale real labels\n",
    "        batch_labels = test_data[4]\n",
    "        batch_labels = batch_labels[test_indexes[k]:test_indexes[k + 1]]\n",
    "        batch_labels = scaler.inverse_transform(batch_labels)\n",
    "        test_rmses.append(root_mean_squared_error(\n",
    "            batch_labels, batch_preds))\n",
    "        test_maes.append(mean_absolute_error(batch_labels, batch_preds))\n",
    "\n",
    "test_rmses = np.asarray(test_rmses)\n",
    "test_maes = np.asarray(test_maes)\n",
    "\n",
    "print('===============METRIC===============')\n",
    "print('rmse = {:.6f}'.format(test_rmses.mean()))\n",
    "print('mae = {:.6f}'.format(test_maes.mean()))\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
